<template>
	<view class="container">
		<!-- 新闻类型选择 -->
		<view class="header">
			<scroll-view class="type-scroll" scroll-x>
				<view class="type-list">
					<view v-for="(item, index) in newsTypes" :key="index"
						:class="['type-item', currentType === item.type ? 'active' : '']"
						@click="changeType(item.type)">
						{{ item.name }}
					</view>
				</view>
			</scroll-view>
			<view class="about-btn" @click="goToAbout">关于</view>
		</view>

		<!-- 新闻列表 -->
		<scroll-view class="news-list" scroll-y @scrolltolower="loadMore" @refresherrefresh="refresh"
			:refresher-enabled="true" :refresher-triggered="isRefreshing">
			<empty-state v-if="showEmpty" :message="emptyMessage" :show-retry="showRetry" @retry="handleRetry" />
			<template v-else>
				<view v-for="(item, index) in newsList" :key="index" class="news-item" @click="goToDetail(item)">
					<view class="news-content">
						<text class="news-title">{{ item.title }}</text>
						<view class="news-info">
							<text class="news-source">{{ item.source }}</text>
							<text class="news-time">{{ item.time }}</text>
						</view>
					</view>
					<image v-if="item.imgsrc" :src="item.imgsrc" class="news-image" mode="aspectFill"></image>
				</view>
				<view v-if="loading" class="loading">加载中...</view>
			</template>
		</scroll-view>
	</view>
</template>

<script>
import { getNewsTypes, getNewsList } from '../../api/news.js';
import EmptyState from '../../components/empty-state/empty-state.vue';

export default {
	components: {
		EmptyState
	},
	data() {
		return {
			newsTypes: [],
			newsList: [],
			currentType: 1,
			currentPage: 1,
			loading: false,
			isRefreshing: false,
			showEmpty: false,
			emptyMessage: '暂无数据',
			showRetry: false
		}
	},
	onLoad() {
		this.getTypes();
		this.getNews();
	},
	methods: {
		// 获取新闻类型
		async getTypes() {
			console.log('开始获取新闻类型...');
			try {
				const result = await getNewsTypes();
				console.log('获取新闻类型结果:', result);
				if (Array.isArray(result)) {
					const [err, res] = result;
					if (!err && res.data.code === 200) {
						this.newsTypes = res.data.data;
						console.log('新闻类型数据更新成功:', this.newsTypes);
						this.showEmpty = false;
					} else {
						console.warn('获取新闻类型失败:', err || res.data);
						uni.showToast({
							title: '获取新闻类型失败',
							icon: 'none'
						});
					}
				}
			} catch (e) {
				console.error('获取新闻类型出错:', e);
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
			}
		},
		// 获取新闻列表
		async getNews(page = 1) {
			console.log(`开始获取新闻列表, 类型: ${this.currentType}, 页码: ${page}`);
			this.loading = true;
			try {
				const [err, res] = await getNewsList(this.currentType, page);
				console.log('获取新闻列表结果:', err || res.data);
				if (!err && res.data.code === 200) {
					if (page === 1) {
						this.newsList = res.data.data;
						console.log('新闻列表已重置');
						// 检查是否有数据
						if (!this.newsList || this.newsList.length === 0) {
							this.showEmpty = true;
							this.emptyMessage = '暂无新闻数据';
							this.showRetry = false;
						} else {
							this.showEmpty = false;
						}
					} else {
						this.newsList = [...this.newsList, ...res.data.data];
						console.log(`已加载更多新闻，当前共${this.newsList.length}条`);
					}
					this.currentPage = page;
				} else {
					console.warn('获取新闻列表失败:', err || res.data);
					if (page === 1) {
						this.showEmpty = true;
						this.emptyMessage = '获取新闻失败';
						this.showRetry = true;
					} else {
						uni.showToast({
							title: '加载更多失败',
							icon: 'none'
						});
					}
				}
			} catch (e) {
				console.error('获取新闻列表出错:', e);
				this.showEmpty = true;
				this.emptyMessage = '网络请求失败';
				this.showRetry = true;
			} finally {
				this.loading = false;
				this.isRefreshing = false;
			}
		},
			// 切换新闻类型
			changeType(type) {
				console.log(`切换新闻类型: ${type}`);
				if (this.currentType === type) {
					console.log('当前已是该类型，无需切换');
					return;
				}
				this.currentType = type;
				this.currentPage = 1;
				console.log('重置页码，开始获取新闻');
				this.getNews();
			},
			// 加载更多
			loadMore() {
				if (this.loading) {
					console.log('正在加载中，忽略加载更多请求');
					return;
				}
				console.log('触发加载更多');
				this.getNews(this.currentPage + 1);
			},
			// 下拉刷新
			refresh() {
				console.log('触发下拉刷新');
				this.isRefreshing = true;
				this.currentPage = 1;
				this.getNews();
			},
			// 跳转到新闻详情
			goToDetail(item) {
				console.log('跳转新闻详情:', item.title);
				// #ifdef H5
				console.log('H5环境，使用window.open打开链接');
				window.open(item.m_url);
				// #endif
				// #ifndef H5
				console.log('非H5环境，使用webview打开链接');
				uni.navigateTo({
					url: `/pages/webview/webview?url=${encodeURIComponent(item.m_url)}`
				});
				// #endif
			},
			// 跳转到关于页面
			goToAbout() {
				console.log('跳转到关于页面');
				uni.navigateTo({
					url: '/pages/about/about'
				});
			}
		}
	}
</script>

<style lang="scss">
.container {
	height: 100vh;
	display: flex;
	flex-direction: column;
}

.header {
	display: flex;
	align-items: center;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
}

.type-scroll {
	height: 80rpx;
	flex: 1;
	background-color: #fff;
}

.about-btn {
	padding: 0 30rpx;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
	color: #007AFF;
}

.type-list {
	display: flex;
	padding: 0 20rpx;
	height: 100%;
}

.type-item {
	padding: 0 30rpx;
	height: 100%;
	line-height: 80rpx;
	font-size: 28rpx;
	color: #333;
	position: relative;

	&.active {
		color: #007AFF;

		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 40rpx;
			height: 4rpx;
			background-color: #007AFF;
			border-radius: 2rpx;
		}
	}
}

.news-list {
	flex: 1;
	background-color: #f8f8f8;
}

.news-item {
	margin: 20rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 10rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.news-content {
	flex: 1;
	margin-right: 20rpx;
}

.news-title {
	font-size: 30rpx;
	color: #333;
	line-height: 1.4;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.news-info {
	margin-top: 10rpx;
	display: flex;
	align-items: center;
}

.news-source,
.news-time {
	font-size: 24rpx;
	color: #999;
}

.news-source {
	margin-right: 20rpx;
}

.news-image {
	width: 200rpx;
	height: 140rpx;
	border-radius: 6rpx;
}

.loading {
	text-align: center;
	padding: 20rpx;
	color: #999;
	font-size: 24rpx;
}
</style>
